let { HttpRequest, globalData, CloudFunction, mfutil, addUserStat } = getApp();

Component({
  mixins: [],
  data: {
    current: null,
    num: 0,   //兴趣个数
    size: 0,    //鞋码index
    gender: '男',   //性别index
    age: 0,         //年龄index
    bodyObj: {
      "memberId": '',
      "fullName": '',
      "genderCode": '',
      "birthDate": '',
      "email": '',
      "shoeSize": '',
      "brandTenure": '',   //品牌生命周期
      "provinceId": "",
      "province": '',
      "cityId": "",
      "city": '',
      "interests": {}
    },
    genderList: ['男', '女'],
    dataTime: '',
    ageList: [],
    sizeList: [],
    question1List: [],
    ageIndex: 0,
    currentStartY: 0,
    currentEndY: 0
  },
  props: {
  },
  async didMount() {
    this.setData({
      question1List: this.props.question1List,
      ageList: this.props.ageList,
      sizeList: this.props.sizeList,
      register: this.props.register,
      interests: this.props.interests,
      formData: this.props.formData
    })
    this.initpage()
  },
  didUpdate() {
    if (this.data.interests !== this.props.interests || globalData.userInfo.shoeSize != this.data.bodyObj.shoeSize || globalData.userInfo.brandTenure != this.data.bodyObj.brandTenure) {
      this.initpage()
    }
    if (this.data.formData != this.props.formData) {
      this.setData({
        formData: this.props.formData,
        bodyObj: {
          "memberId": globalData.userInfo.memberId,
          "fullName": this.props.formData ? this.props.formData.name : globalData.userInfo.fullName,
          "genderCode": this.props.formData ? this.props.formData.genderCode : globalData.userInfo.genderCode,
          "birthDate": globalData.userInfo.birthDate,
          "email": globalData.userInfo.email,
          "shoeSize": globalData.userInfo.shoeSize,
          "brandTenure": globalData.userInfo.brandTenure,   //品牌生命周期
          "provinceId": globalData.userInfo.userProvinceCode,
          "province": globalData.userInfo.province,
          "cityId": globalData.userInfo.userCityCode,
          "city": globalData.userInfo.city,
          "interests": globalData.userInfo.interests
        }
      })
    }
    if (this.data.current != this.props.currentItem) {
      this.setData({
        current: this.props.currentItem,
      })
    }
  },
  didUnmount() {
  },
  methods: {
    /**
     * 初始化页面
     * @description question1List问卷1 内容初始化
     * @description num   问卷1选择个数,
     * 
     */
    async initpage() {
      //品牌生命周期
      let { sizeList, ageList, question1List, formData } = this.data;
      let num = 0;
      //value值填入下标
      let sizeIndex = sizeList.findIndex((item) => { return item == globalData.userInfo.shoeSize });
      sizeIndex = sizeIndex != -1 ? sizeIndex : 0;
      let genderIndex = (globalData.userInfo.genderCode == '100000001') ? 0 : 1;
      let ageIndex = ageList.findIndex((item) => { return item == globalData.userInfo.brandTenure });
      ageIndex = ageIndex != -1 ? ageIndex : 0
      //问卷1兴趣数据初始化   active
      let interests = this.props.interests;
      this.setData({
        interests
      })
      question1List.forEach((item, value) => {
        delete item.selected;
      });
      if (interests != {}) {
        question1List.forEach((item, value) => {
          for (let i in interests) {
            if (i == item.sync_clm_value) {    //***************************88
              item.selected = true;
              num += 1
            }
          }
        })
      }
      this.setData({
        question1List,
        num,
        current: this.props.currentItem,   //目标问卷编号123
        size: sizeIndex,
        gender: genderIndex,
        age: globalData.userInfo.brandTenure,     //品牌周期
        ageIndex,
        bodyObj: {
          "memberId": globalData.userInfo.memberId,
          "fullName": formData ? formData.name : globalData.userInfo.fullName,
          "genderCode": formData ? formData.genderCode : globalData.userInfo.genderCode,
          "birthDate": globalData.userInfo.birthDate,
          "email": globalData.userInfo.email,
          "shoeSize": globalData.userInfo.shoeSize,
          "brandTenure": globalData.userInfo.brandTenure,   //品牌生命周期
          "provinceId": globalData.userInfo.userProvinceCode,
          "province": globalData.userInfo.province,
          "cityId": globalData.userInfo.userCityCode,
          "city": globalData.userInfo.city,
          "interests": globalData.userInfo.interests
        }
      })
    },
    /**
     * 
     * @param {*} event 问卷3 
     */
    onChange1(event) {
      let ageIndex = event.detail.value[0];
      this.setData({
        ageIndex: ageIndex
      })
    },
    /**
     * 
     * @param {*} event 问卷2
     */
    onChange2(event) {
      let sizeIndex = event.detail.value[0];
      this.setData({
        size: sizeIndex,
      })
    },
    /**
     * 
     * @param {*} event 问卷1item点击选择
     */
    selectItem(event) {
      let { item } = event.currentTarget.dataset;
      let { question1List, num } = this.data;
      question1List.forEach((value) => {
        if (num < 3 && value.option_number == item && Boolean(value.selected) == false) {
          value.selected = true
          num += 1
        } else if (value.option_number == item && Boolean(value.selected) == true) {
          delete (value.selected)
          num -= 1
        } else if (Boolean(value.selected) == false && num >= 3 && value.option_number == item) {
          my.alert({
            content: '您最多只能选择3个兴趣!'
          })
        }
      });
      this.setData({
        question1List,
        num
      })
    },
    /**
     * 问卷1提交
     */
    async sucQuestion1() {
      let { question1List, bodyObj, formData } = this.data;
      let interests = {};
      let num = 0;
      question1List.forEach((item) => {
        if (item.selected == true) {
          interests[item.sync_clm_value] = '1'     //后续需要修改*****************************************************8
          // item.selected = false;
          num++;
        }
      })
      let reg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/;
      if (bodyObj.email) {
        if (!reg.test(bodyObj.email) && bodyObj.email != '') {
          my.showToast({
            content: '请填写正确格式邮箱',
            duration: 1000
          });
          return
        }
      }
      bodyObj.interests = interests;
      let path = `/vans-family/api/v2.1/project/vansFamily/clm/forward?url=/v1/member/api/tmall/update&type=PUT`
      let submitData = []
      let res = await HttpRequest(path, 'POST', '', bodyObj);
      if (res.data.resultCode == 0) {
        this.setData({
          question1List,
          current: null,
          num: 0
        })
        this.props.onSucQuestion && this.props.onSucQuestion(question1List);
        this.props.onQueryMember && this.props.onQueryMember();
        if (num > 0) {
        }
        this.props.onOpenQuest && this.props.onOpenQuest(null);
        this.props.onSaveActiveFn && this.props.onSaveActiveFn(false);
        let options = {
          name: 'memberinfoData.interests',
          value: interests
        }
        this.props.onQuestionChange && this.props.onQuestionChange(options)
      } else {
        my.alert({
          content: res.data.resultDesc
        })
        // mfutil.launchErrPage(53001)
      }
      // }

      // 自定义埋点
      let customAccessoptions = {
        customType: '更新个人兴趣'
      }
      console.log('更新个人兴趣');
      
      let tracks = addUserStat(customAccessoptions)
    },

    /**
     * 问卷2提交
     */
    async sucQuestion3() {
      let { size, sizeList, gender, bodyObj } = this.data;
      bodyObj.shoeSize = sizeList[size]
      let path = `/vans-family/api/v2.1/project/vansFamily/clm/forward?url=/v1/member/api/tmall/update&type=PUT`;
      let reg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/;
      if (bodyObj.email) {
        if (!reg.test(bodyObj.email) && bodyObj.email != '') {
          my.showToast({
            content: '请填写正确格式邮箱',
            duration: 1000
          });
          return
        }
      }
      let res = await HttpRequest(path, 'POST', '', bodyObj);
      if (res.data.resultCode == 0) {
        this.setData({
          current: null
        })
        this.props.onOpenQuest && this.props.onOpenQuest(null);
        this.props.onSaveActiveFn && this.props.onSaveActiveFn(false);
        this.props.onQueryMember && this.props.onQueryMember();
        let options = {
          name: 'memberinfoData.shoeSize',
          value: sizeList[size]
        }
        this.props.onQuestionChange ? this.props.onQuestionChange(options) : ''
      } else {
        my.alert({
          content: res.data.resultDesc
        })
        // mfutil.launchErrPage(53001)
      }
      // }

      // 自定义埋点
      let customAccessoptions = {
        customType: '更新尺码'
      }

      let tracks = addUserStat(customAccessoptions)

    },
    /**
     * 问卷3提交
     */
    async sucQuestion2() {
      let { age, ageList, bodyObj, ageIndex } = this.data;
      bodyObj.brandTenure = ageList[ageIndex];
      let path = `/vans-family/api/v2.1/project/vansFamily/clm/forward?url=/v1/member/api/tmall/update&type=PUT`;
      let reg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/;
      if (bodyObj.email) {
        if (!reg.test(bodyObj.email) && bodyObj.email != '') {
          my.showToast({
            content: '请填写正确格式邮箱',
            duration: 1000
          });
          return
        }
      }
      let res = await HttpRequest(path, 'POST', '', bodyObj);
      if (res.data.resultCode == 0) {
        this.setData({
          age: 0,
          gender: 0,
          current: null
        })
        let options = {
          name: 'memberinfoData.brandTenure',
          value: ageList[ageIndex]
        }
        this.props.onQuestionChange && this.props.onQuestionChange(options);
        this.props.onOpenQuest && this.props.onOpenQuest(null);
        this.props.onQueryMember && this.props.onQueryMember();
        this.props.onSaveActiveFn && this.props.onSaveActiveFn(false);
      } else {
        my.alert({
          content: res.data.resultDesc
        })
      }

      // 自定义埋点
      let customAccessoptions = {
        customType: '更新穿鞋年龄'
      }

      let tracks = addUserStat(customAccessoptions)
    },
    /**
     * 任务完成
     * @param {*} options 
     */
    async finishedTile(options) {
      let { question1List, bodyObj } = this.data;
      question1List.forEach((value, index) => {
        for (let i in bodyObj.interests) {
          if (value.sync_clm_value == i) {
            value.selected = true
          }
        }
      })
      let index = options;
      let { id } = this.data.template[index];
      let parmasObj = {
        member_id: globalData.userInfo.memberId,
        member_id_type: 1,
      }
      let selectList = {};
      if (index == 0) {
        selectList = question1List
      } else if (index == 1) {
        selectList = [
          {
            "type": "text",
            "value": bodyObj.shoeSize,
            "desc": ""
          }
        ]
      } else if (index == 2) {
        selectList = [
          {
            "type": "text",
            "value": Number(new Date(bodyObj.birthDate).getFullYear()) + Number(bodyObj.brandTenure),
            "desc": ""
          }
        ]
      }
      let pathTile = `/vans-family/api/v2.1/project/vansFamily/cms/forward/get?url=/v2/cms/api/tile/${id}`;
      let res = await HttpRequest(pathTile, 'POST', parmasObj, {});
      if (res.data.code == 0 && res.data.data.related.done == 0) {
        let question = res.data.data.tile_info.question;
        let time = new Date(+new Date() + 8 * 3600 * 1000).toJSON().substr(0, 19).replace("T", " ").replace(/\-/g, "/")
        let bodyObjdone = {
          member_id_type: 1,
          do_datetime: time,
          question,
          options: selectList
        }
        let pathdone = `/vans-family/api/v2.1/project/vansFamily/cms/forward/post?url=/v1/cms/api/tile/${res.data.data.tile_info.type}/${id}/done?member_id=${globalData.userInfo.memberId}`;
        let result = await HttpRequest(pathdone, 'POST', '', bodyObjdone);
      }
    },
    //退出
    exitCard() {
      this.setData({
        current: null
      })
      this.props.onOpenQuest(null, 'a');
    },
    //弹窗事件
    onTouchStartFn(event) {
      let currentStartY = event.changedTouches[0].clientY;
      this.setData({
        currentStartY
      })
    },
    onTouchEndFn(event) {
      let { currentStartY } = this.data;
      let currentEndY = event.changedTouches[0].clientY;
      this.setData({
        currentEndY
      })
      if (currentEndY - currentStartY > 500) {
        this.exitCard();
      }
    }
  },
});
